package com.sgj.sync;

/**
 * @Author: Guoji Shen
 * @Date: 2021/8/5 8:54
 */
public class ThreadDemo1 {

    public static void main(String[] args) {
        Share share = new Share();

        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                try {
                    share.incr();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, "AA").start();

        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                try {
                    share.decr();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, "BB").start();

        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                try {
                    share.incr();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, "CC").start();

        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                try {
                    share.decr();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, "DD").start();
    }
}

class Share {
    // 初始值
    private int number;

    // +1的方法
    public synchronized void incr() throws InterruptedException {
        // 判断number是否为0，如果不是0，等待
        while (number != 0) {
            this.wait();
        }
        // 如果number为0，+1
        number ++;
        System.out.println(Thread.currentThread().getName() + " :: " + number);
        // 通知其他线程
        this.notifyAll();
    }
    // -1的方法
    public synchronized void decr() throws InterruptedException {
        // 判断number是否为0，如果不为1，等待
        while (number != 1) {
            this.wait();
        }
        // 如果number为1，-1
        number --;
        System.out.println(Thread.currentThread().getName() + " :: " + number);
        // 通知其他线程
        this.notifyAll();
    }
}